package com.jly.edu.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jly.edu.common.dto.SysMenuDto;
import com.jly.edu.common.lang.Const;
import com.jly.edu.common.lang.Result;
import com.jly.edu.common.param.SysMenuParam;
import com.jly.edu.common.validated.SaveGroup;
import com.jly.edu.common.validated.UpdateGroup;
import com.jly.edu.entity.SysMenu;
import com.jly.edu.entity.SysRoleMenu;
import com.jly.edu.entity.SysUser;
import com.jly.edu.service.SysCommonService;
import com.jly.edu.service.SysMenuService;
import com.jly.edu.service.SysRoleMenuService;
import com.jly.edu.service.SysUserService;
import com.jly.edu.utils.ConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者：纪联友
 * @since 2021-10-23
 */
@RestController
@RequestMapping("/sys-menu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysCommonService sysCommonService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 根据 menu id 获取menu
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    public Result info(@PathVariable(name = "id") Long id){

        return  Result.success(sysMenuService.getById(id));
    }

    /**
     * 获取所有菜单 无需分页
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    public Result getAllMenuList(){

        //获取menu list 方法
        List<SysMenu> allMenuList = sysMenuService.getAllMenuList();

        return Result.success(allMenuList);
    }

    /**
     * 保存菜单
     * @param param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:menu:save')")
    @PostMapping("/save")
    public Result saveMenu(@Validated(SaveGroup.class) @RequestBody SysMenuParam param){

        SysMenu sysMenu = ConverUtil.convert(param, SysMenu.class);
        sysMenu.setCreateTime(LocalDateTime.now());
        sysMenu.setStatus(Const.STATUS_ON);
        Integer maxOrderNum = sysCommonService.maxOrderNum(param.getParentId());
        if(maxOrderNum == null){
            maxOrderNum = 0;
        }
        maxOrderNum = maxOrderNum + 1;
        sysMenu.setOrderNum(maxOrderNum);
        sysMenuService.save(sysMenu);
        return Result.success(sysMenu);
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('sys:menu:delete')")
    public Result deleteMenu(@PathVariable("id") Long id){
        if(id == null){
            return Result.fail("菜单id不能为空");
        }
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if(count > 0){
            return Result.fail("请先删除子菜单");
        }
        // 先清除与该菜单相关联的权限缓存
        sysCommonService.clearUserAuthorityInfoByMenuId(id);
        sysMenuService.removeById(id);
        //同步删除 menu和role的中间表信息
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id",id));

        return Result.success("");
    }



    /**
     * 修改菜单
     * @param param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:menu:update')")
    @PostMapping("/update")
    public Result updateMenu(@Validated(UpdateGroup.class) @RequestBody SysMenuParam param){
        param.setUpdateTime(LocalDateTime.now());
        sysMenuService.updateById(ConverUtil.convert(param,SysMenu.class));
        //删除所有与当前菜单相关的权限缓存
        sysCommonService.clearUserAuthorityInfoByMenuId(param.getId());
        return Result.success(param);
    }

    /**
     * 获取当前用户的菜单栏以及权限
     */
    @GetMapping("/nav")
    public Result nav(Principal principal) {
        String username = principal.getName();
        SysUser sysUser = sysUserService.getByUsername(username);
        // ROLE_Admin,sys:user:save
        String[] authoritys = StringUtils.tokenizeToStringArray(sysCommonService.getUserAuthorityInfo(sysUser.getId()), ",");
        return Result.success(
                MapUtil.builder()
                .put("nav", sysMenuService.getCurrentUserNav())
                        .put("authoritys", authoritys)
                        .map());
    }


}
